package cn.lisens.serial.service;

import org.springframework.stereotype.Service;

import com.fazecast.jSerialComm.SerialPort;

@Service
public class SerialPortService {

	private SerialPort serialPort;

    // 初始化串口
    public void initSerialPort(String portName, int baudRate) {
        serialPort = SerialPort.getCommPort(portName);
        serialPort.setBaudRate(baudRate);
        serialPort.setNumDataBits(8);
        serialPort.setNumStopBits(1);
        serialPort.setParity(SerialPort.NO_PARITY);

        if (serialPort.openPort()) {
            System.out.println("串口打开成功: " + portName);
        } else {
            throw new RuntimeException("串口打开失败");
        }
    }

    // 发送AT指令
    public String sendATCommand(String command, int timeoutMs) {
        if (!serialPort.isOpen()) {
            throw new IllegalStateException("串口未打开");
        }

        // 发送指令（需添加回车换行符 \r\n）
        byte[] cmdBytes = (command + "\r\n").getBytes();
        serialPort.writeBytes(cmdBytes, cmdBytes.length);

        // 读取响应
        try {
            Thread.sleep(timeoutMs); // 等待设备响应
            byte[] buffer = new byte[serialPort.bytesAvailable()];
            serialPort.readBytes(buffer, buffer.length);
            return new String(buffer);
        } catch (Exception e) {
            throw new RuntimeException("AT指令通信异常", e);
        }
    }

    // 关闭串口
    public void closePort() {
        if (serialPort != null && serialPort.isOpen()) {
            serialPort.closePort();
        }
    }
}
